export default class CollisionSystem {
  constructor () {
    this.objects = []
    this.currentCollisions = new Map() // 当前帧碰撞 {key: {obj1, obj2}}
    this.lastCollisions = new Map() // 上一帧碰撞
    this.stayCounts = new Map() // 持续碰撞计数 {key: frames}
  }

  addObject (object) {
    if (!this.objects.includes(object)) {
      this.objects.push(object)
      // 初始化物体碰撞状态
      object.__collisionStates = new Map() // {otherObjId: state}
    }
  }

  update () {
    this.currentCollisions.clear()

    // 1. 检测所有碰撞
    for (let i = 0; i < this.objects.length; i++) {
      for (let j = i + 1; j < this.objects.length; j++) {
        const obj1 = this.objects[i]
        const obj2 = this.objects[j]

        if (this.checkCollision(obj1, obj2)) {
          const key = this.getCollisionKey(obj1, obj2)
          this.currentCollisions.set(key, { obj1, obj2 })
        }
      }
    }

    // 2. 处理碰撞事件
    this.handleCollisionEvents()

    // 3. 更新状态
    this.lastCollisions = new Map(this.currentCollisions)
  }

  handleCollisionEvents () {
    // 处理新碰撞（Enter）
    this.currentCollisions.forEach(({ obj1, obj2 }, key) => {
      if (!this.lastCollisions.has(key)) {
        this.triggerCollisionEnter(obj1, obj2)
        this.triggerCollisionEnter(obj2, obj1)
        this.stayCounts.set(key, 1) // 初始化持续计数
      } else {
        // 持续碰撞（Stay）
        const count = this.stayCounts.get(key) || 0
        this.stayCounts.set(key, count + 1)

        // 每N帧触发一次Stay（优化性能）
        if (count % 5 === 0) {
          this.triggerCollisionStay(obj1, obj2)
          this.triggerCollisionStay(obj2, obj1)
        }
      }
    })

    // 处理碰撞结束（Exit）
    this.lastCollisions.forEach(({ obj1, obj2 }, key) => {
      if (!this.currentCollisions.has(key)) {
        this.triggerCollisionExit(obj1, obj2)
        this.triggerCollisionExit(obj2, obj1)
        this.stayCounts.delete(key)
      }
    })
  }

  // 触发回调的辅助方法
  triggerCollisionEnter (obj, other) {
    if (obj.onCollisionEnter) obj.onCollisionEnter(other)
    if (obj.dispatchEvent) {
      obj.dispatchEvent({ type: 'collisionenter', other })
    }
    obj.__collisionStates.set(other.uuid, 'enter')
  }

  triggerCollisionStay (obj, other) {
    if (obj.onCollisionStay) obj.onCollisionStay(other)
    if (obj.dispatchEvent) {
      obj.dispatchEvent({ type: 'collisionstay', other })
    }
    obj.__collisionStates.set(other.uuid, 'stay')
  }

  triggerCollisionExit (obj, other) {
    if (obj.onCollisionExit) obj.onCollisionExit(other)
    if (obj.dispatchEvent) {
      obj.dispatchEvent({ type: 'collisionexit', other })
    }
    obj.__collisionStates.delete(other.uuid)
  }

  // 其他辅助方法
  getCollisionKey (obj1, obj2) {
    return [obj1.uuid, obj2.uuid].sort().join('-')
  }

  checkCollision (obj1, obj2) {
    // 实现你的碰撞检测逻辑
    obj1.updateMatrixWorld()
    obj2.updateMatrixWorld()
    const box1 = new GC.Box3().setFromObject(obj1)
    const box2 = new GC.Box3().setFromObject(obj2)
    return box1.intersectsBox(box2)
  }
}

// function startCollisionSystem() {
//   // 使用示例
//    collisionSystem = new CollisionSystem();
//   // 在动画循环中更新
//   function animate() {
//     collisionSystem.update();
//     requestAnimationFrame(animate);
//   }
//   animate();
// }
// const parentNode = handelmodel.model.scene;
// const childNode = handelmodel2.model.scene;
// collisionSystem.addObject(parentNode);
//  collisionSystem.addObject(childNode);

//   // 注册回调方式1：直接属性
// parentNode.onCollisionEnter = (other) => {
//   console.log('parentNode 开始碰撞:', other.name);
// };
// parentNode.onCollisionStay = (other) => {
//   console.log('parentNode 持续碰撞:', other.name);
// };
// parentNode.onCollisionExit = (other) => {
//   console.log('parentNode 结束碰撞:', other.name);
// };
